package com.newenergy.wisehome.gateway.device;


import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.manager.MyThreadManager;
import com.newenergy.wisehome.data.bean.BLDeviceInfo;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.ormlite.dao.BLDeviceInfoDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyDao;
import com.newenergy.wisehome.gateway.common.BLModelUtil;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.ui.adapter.ShareAdapter;
import com.newenergy.wisehome.ui.fragment.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.broadlink.sdk.data.controller.BLDNADevice;
import me.yokeyword.fragmentation.ISupportFragment;

/**
 * 绑定网关家庭
 */
public class BindFamilyFragment extends BaseFragment {


    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.tv_back)
    TextView mTvBack;
    @BindView(R.id.tv_page)
    TextView mTvPage;
    @BindView(R.id.tv_select)
    TextView mTvSelect;
    @BindView(R.id.divider1)
    View mDivider1;
    @BindView(R.id.btn_next)
    Button mBtnNext;
    @BindView(R.id.recyclerView)
    EasyRecyclerView mRecyclerView;
    private ShareAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private int mCurrPosition = 0;
    private Family mFamily;

    //0表示直接进来绑定设备 1表示配网发现新设备后绑定设备
    private int bindType = 0;

    public static final String BIND_TYPE = "BIND_TYPE";


    @Override
    public int getLayoutId() {
        return R.layout.fragment_bind_family;
    }

    @Override
    public void init(View rootView) {
        mTvPage.setText("家庭管理");
        initRecycleView();
        Bundle arguments = getArguments();
        if (arguments != null) {
            bindType = arguments.getInt(BIND_TYPE);
            if (bindType != 1) {
                bindType = 0;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        FamilyDao familyDao = new FamilyDao(getContext());
        List<Family> families = familyDao.getFamiliesByType(1);
        if (families != null && families.size() > 0) {
            List<Family> familyList = new ArrayList<>();
            for (Family family : families) {
                if (TextUtils.isEmpty(family.getBlFamilyId())) {
                    familyList.add(family);
                }
            }
            mAdapter.refreshData(familyList);
            mCurrPosition = 0;
            setCurrentItem();
        }
        getNoFamilyLocalBLDevice();
    }

    private void getNoFamilyLocalBLDevice() {
        if (bindType != 1) {
            BLDeviceInfoDao deviceInfoDao = new BLDeviceInfoDao(getContext());
            List<BLDeviceInfo> deviceInfos = deviceInfoDao.getAllBLDeviceInfo();
            if (deviceInfos != null && deviceInfos.size() > 0) {
                for (BLDeviceInfo deviceInfo : deviceInfos) {
                    if (TextUtils.isEmpty(deviceInfo.getFamilyId()) && deviceInfo.getBlType() == 0) {
                        BLDNADevice dnaDevice = BLModelUtil.toDNADevice(deviceInfo);
                        BLLocalFamilyManager.getInstance().mLocalDnaDevice = dnaDevice;
                        break;
                    }
                }
            }
        }
    }


    @OnClick({R.id.btn_back, R.id.tv_back, R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;
            case R.id.tv_back:
                doBack();
                break;
            case R.id.btn_next:
                bindFamily();
                break;
        }
    }


    private void initRecycleView() {
        Context context = getContext();
        mAdapter = new ShareAdapter(context);
        mRecyclerView.setAdapter(mAdapter);
        mLayoutManager = new LinearLayoutManager(context);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter.setOnItemClickListener(position -> {
            mCurrPosition = position;
            setCurrentItem();
            Log.i(TAG, "OnItemClick: " + mFamily.getName());

        });
    }

    private void setCurrentItem() {
        List<Family> datas = mAdapter.getAllData();
        if (datas.size() < 1) {
            return;
        }
        mCurrPosition = mCurrPosition >= datas.size() ? 0 : mCurrPosition;
        for (Family framily : datas) {
            framily.setChecked(false);
        }
        mFamily = mAdapter.getItem(mCurrPosition);
        mFamily.setChecked(true);
        mAdapter.notifyDataSetChanged();
    }

    private void bindFamily() {
        BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
        if (!familyManager.checkAppState()) {
            return;
        }

        if (mFamily == null) {
            toast("当前没有可绑定网关的家庭");
            return;
        }
        if (familyManager.mLocalDnaDevice == null) {
            toast("当前没有可绑定网关的设备");
            return;
        }
//        familyManager.showLoading("正在绑定网关，请稍等。。。");
        MyThreadManager.getInstance().doTask(() -> {
            familyManager.createBLFamily(mFamily);
        });
    }

    public static ISupportFragment newInstance(int bindType) {
        BindFamilyFragment fragment = new BindFamilyFragment();
        Bundle args = new Bundle();
        args.putInt(BIND_TYPE, bindType);
        fragment.setArguments(args);
        return fragment;
    }
}
